package com.jkj.http.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.jkj.http.entity.Operator;
import com.jkj.http.sys.service.PermissionService;
import com.jkj.utils.OperatorProvider;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 权限验证过滤器
 *
 * @author zhoujunwen
 */
@Component
public class AuthorizeCheckedInterceptor implements HandlerInterceptor {
	@Autowired
	private PermissionService service;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
		if (handler.getClass().isAssignableFrom(HandlerMethod.class)) {
			AuthorizeChecked authorizeChecked = ((HandlerMethod) handler).getMethodAnnotation(AuthorizeChecked.class);
			if (authorizeChecked == null)
				return true;
			if (authorizeChecked.ignore()) {
				return true;
			}
			Operator operator = OperatorProvider.getCurrent(request.getSession());
			if (operator == null) {
				response.getWriter().print("<script>alert('对不起，Session已过期，请重新登录');</script>");
				return false;
			}
			String userId = operator.getUserId();
			String action = request.getRequestURI();

			boolean hasPermission = service.actionValidate(userId, action);
			if (!hasPermission) {
				response.getWriter().print("<script>alert('对不起，您没有权限访问当前页面。');</script>");
				return false;
			}
			return true;
		}
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {

	}

}
